<template>
  <div>
    <home>
      <div slot="conter" class="topaa" data-attr="添加商品">
        <a href="#">
          <h2>添加商品</h2>
        </a>
      </div>
      <div slot="nav-menu">
        <el-submenu index="1-1">
          <template slot="title">
            <i class="el-icon-menu"></i>
            <span>商品系列</span>
          </template>
          <el-menu-item-group>
            <template slot="title">专场</template>
            <el-menu-item index="1-2" @click="AuctionClick('/auction/index/')">商品专场</el-menu-item>
          </el-menu-item-group>
          <el-menu-item-group index="1-3" title="添加系列">
            <template slot="title">添加列表</template>
            <el-menu-item index="1-4-2">添加商品</el-menu-item>
          </el-menu-item-group>
        </el-submenu>
      </div>
      <div slot="context">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="商品标题" prop="title">
            <el-input v-model="ruleForm.title"></el-input>
          </el-form-item>
          <el-form-item label="商品状态" prop="status">
            <el-select v-model="ruleForm.status" placeholder="请选择活动区域">
              <el-option label="未开拍" value="1"></el-option>
              <el-option label="预展中" value="2"></el-option>
              <el-option label="拍卖中" value="3"></el-option>
              <el-option label="已结束" value="4"></el-option>
              <el-option label="流拍" value="5"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="起拍价" prop="start_price">
            <el-input v-model="ruleForm.start_price" type="number" min="100"></el-input>
          </el-form-item>
          <el-form-item label="参考价">
            <el-col :span="11">
              <el-form-item prop="reserve_price">
                <el-input v-model="ruleForm.reserve_price" type="number" min="100" placeholder="参考低价"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="line" :span="2">-</el-col>
            <el-col :span="11">
              <el-form-item prop="highest_price">
                <el-input v-model="ruleForm.highest_price" type="number" placeholder="参考高价"></el-input>
              </el-form-item>

            </el-col>
          </el-form-item>
          <el-form-item label="单品保证金" prop="deposit">
            <el-input v-model="ruleForm.deposit" type="number" min="100"></el-input>
          </el-form-item>
          <el-form-item label="加价幅度" prop="unit">
            <el-input v-model="ruleForm.unit" type="number" min="100"></el-input>
          </el-form-item>
          <el-form-item label="商品封面" prop="type">
            <el-upload
                    class="upload-demo"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :http-request="handleChange"
                    :on-remove="handleRemove"
                    :file-list="fileList"
                    list-type="picture">
              <el-button size="small" type="primary" v-model="fileList">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>


    </home>
  </div>
</template>

<script>
  import Home from "./Home";
  import {TX_COS, AddHomeAuctionItem} from "network/home"
  import COS from "cos-js-sdk-v5";

  export default {
    name: "HomeItemAuction",
    components: {Home},
    data() {
      return {
        ruleForm: {
          title: '',
          status: '1',
          start_price: '100',
          reserve_price: '100',
          highest_price: '',
          deposit: '100',
          unit: '100',
          cover: ''
        },
        rules: {
          title: [
            {required: true, message: '请输入商品名称', trigger: 'blur'},
            {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
          ],
          status: [
            {message: '请选择商品状态', trigger: 'blur'}
          ],
          start_price: [
            {required: true, message: '请填写起拍价', trigger: 'blur'}
          ],
          reserve_price: [
            {required: true, message: '请填写参考低价', trigger: 'blur'}

          ],
          highest_price: [
            {required: true, message: '请填写参考高价', trigger: 'blur'}
          ],
          deposit: [
            {required: true, message: '请填写单场保证金', trigger: 'blur'}
          ],
          unit: [
            {required: true, message: '请填写加价幅度', trigger: 'blur'}
          ],
          type: [{required: true, validator: this.valiimage, trigger: 'change'}],
        },
        fileList: [],
        is_file: false,
      };
    },
    methods: {
      AuctionClick(url) {
        let iid = this.$route.params.aid
        let auction_list = this.$route.query.goods
        this.$router.push({
          path: url + iid, query: {
            goods: auction_list
          }
        })
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let that = this
            TX_COS().then(data => {
                  const cos = new COS({
                    // 必选参数
                    getAuthorization: (options, callback) => {
                      const obj = {
                        TmpSecretId: data.credentials.tmpSecretId,
                        TmpSecretKey: data.credentials.tmpSecretKey,
                        XCosSecurityToken: data.credentials.sessionToken,
                        StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
                        ExpiredTime: data.expiredTime // 时间戳，单位秒，如：1580000900
                      }
                      callback(obj)
                    }
                  })
                  cos.putObject({
                    Bucket: 'wx-1304867879', /* 必须 */
                    Region: 'ap-guangzhou',     /* 存储桶所在地域，必须字段 */
                    Key: that.fileList[0].name,              /* 必须 */
                    StorageClass: 'STANDARD',
                    Body: that.fileList[0].file, // 上传文件对象
                    onProgress: function (progressData) {

                      console.log(JSON.stringify(progressData));
                    }
                  }, function (err, data) {
                    that.ruleForm.cover = 'https://wx-1304867879.cos.ap-guangzhou.myqcloud.com/' + that.fileList[0].name
                    AddHomeAuctionItem(that.ruleForm, that.$route.params.aid).then(res => {
                      if (res.status) {
                        let auction_list = JSON.parse(decodeURIComponent(that.$route.query.goods));
                        let iid = that.$route.params.aid
                        auction_list.goods = auction_list.goods.concat(res.message)
                        let goods = encodeURIComponent(JSON.stringify(auction_list))
                        that.$router.push({
                          path: '/auction/index/' + iid, query: {goods}
                        }).catch(err => {
                        })

                      } else {
                        console.log(res.message);
                      }
                    }, err => {
                      console.log(err);
                    })
                    console.log(that.ruleForm, that.fileList);
                  });
                }
            )
            console.log(this.fileList);
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      // 获取文件对象
      handleChange(file, fileList) {
        this.fileList[0] = {
          file: file.file,
          name: this.randomString() + '.jpg'
        }
        this.is_file = true
        console.log(this.fileList);
      },
      randomString() {
        return Math.random().toString(36).slice(-8) + String(new Date().getTime())
      },
      handleRemove(file, fileList) {
        console.log(file.name);
      },
      valiimage(rule, value, callback) {
        if (!this.is_file) {
          callback(new Error('请上传封面图片'));
        } else {
          callback()
        }
      }
    }
  }
</script>

<style scoped>
  .demo-ruleForm {
    background-color: #ffffff;
    padding: 100px 300px;

  }

  .line {
    text-align: center;
  }
</style>